package org.example;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author cxu
 * @version 1.0.0
 * @description 简单模式-消息生产者
 * @date 2021年09月19日 11:22:00
 */
public class MessageProducer_Topic {

    public static void sendMessage() throws IOException, TimeoutException {
        // 1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 2.设置参数
        // ip，默认为本地localhost
        connectionFactory.setHost("127.0.0.1");
        // 端口，默认值5672
        connectionFactory.setPort(5672);
        // 虚拟机,默认值/
        connectionFactory.setVirtualHost("my_vhost");
        // 账号,默认值guest
        connectionFactory.setUsername("admin");
        // 密码,默认值guest
        connectionFactory.setPassword("admin");
        // 3.创建连接 Connection
        Connection connection = connectionFactory.newConnection();
        // 4.创建Channel
        Channel channel = connection.createChannel();
        // 5.常见交换机
        /**
         * 参数说明：
         * 1.exchange：交换机类型
         * 2.type：交换机类型
         *     DIRECT("direct"),定向
         *     FANOUT("fanout"),发送到所有绑定的队列
         *     TOPIC("topic"),通配符的方式
         *     HEADERS("headers");参数匹配
         * 3.durable：是否持久化
         * 4.autoDelete：是否自动删除
         * 5.internal：内部使用，一般为false
         * 6.arguments：参数
         */
        String exchangeName = "test_topic";
        channel.exchangeDeclare(exchangeName,BuiltinExchangeType.TOPIC,true,false,false,null);
        // 6.创建队列
        String queue1 = "test_topic_queue1";
        String queue2 = "test_topic_queue2";
        channel.queueDeclare(queue1,true,false,false,null);
        channel.queueDeclare(queue2,true,false,false,null);
        // 7.绑定队列和交换机
        /**
         * 参数说明：
         * 1.queue:队列名称
         * 2.exchange：交换机名称
         * 3.routingKey:路由键，绑定规则
         * 如果交换机的类型为fanout，routingKey设置为""
         */
        // 订单相关信息、info信息存入队列1
        channel.queueBind(queue1,exchangeName,"*.info.*");
        channel.queueBind(queue1,exchangeName,"order.#");
        // 订单错误信息、支付信息存入队列2
        channel.queueBind(queue2,exchangeName,"order.error.*");
        channel.queueBind(queue2,exchangeName,"pay.#");
        // 8.发送消息到交换机
        String message = "Topic模式消息";
        // 发送不同RoutingKey类型的消息，观察exchange会怎么处理
        channel.basicPublish(exchangeName,"test.info.test", null,message.getBytes());
        channel.basicPublish(exchangeName,"order.error.select", null,message.getBytes());
        channel.basicPublish(exchangeName,"order.error.select.success", null,message.getBytes());
        channel.basicPublish(exchangeName,"pay.test", null,message.getBytes());
        // 9.释放资源
        channel.close();
        connection.close();
    }
}
